<script setup lang="jsx">
import { computed, reactive, ref } from 'vue';
import { useElementSize } from '@vueuse/core';
import { parseTime } from '@/utils';
import {
  autoDryProcessbatchAudit,
  autoDryProcessbatchRevoke,
  autoDryProcessdelete,
  autoDryProcessoutbound,
  autoDryProcesstask,
  planautoDryProcessselect
} from '@/service/api/modules/erp';
import Modal from '@/components/common/modal.vue';
import Form from '@/components/common/form.vue';
import Search from './modules/search.vue';

const searchParams = ref({
  matNo: '',
  state: '',
  auditingState: ''
});

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const columns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 100,
    align: 'center',
    checked: true
  },
  {
    key: 'matNo',
    dataIndex: 'matNo',
    title: '物料编号',
    width: 230,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'failureState',
    dataIndex: 'failureState',
    title: '过期状态',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.failureState == 1) {
        return '正常';
      }
      if (record.failureState == 2) {
        return '即将过期';
      }
      if (record.failureState == 3) {
        return '已过期';
      }
      if (record.failureState == 4) {
        return '库存不足';
      }
    }
  },
  {
    key: 'auditingState',
    dataIndex: 'auditingState',
    title: '审核状态',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.auditingState == 1) {
        return '未审核';
      }
      if (record.failureState == 2) {
        return '已审核';
      }
    }
  },
  {
    key: 'specif',
    dataIndex: 'specif',
    title: '物料规格',
    width: 220,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inventory',
    dataIndex: 'inventory',
    title: '库存',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'productionTime',
    dataIndex: 'productionTime',
    title: '生产时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.productionTime == null) {
        return null;
      }
      return parseTime(record.productionTime);
    }
  },
  {
    key: 'expirationTime',
    dataIndex: 'expirationTime',
    title: '失效时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.expirationTime == null) {
        return null;
      }
      return parseTime(record.expirationTime);
    }
  },

  {
    key: 'storageTime',
    dataIndex: 'storageTime',
    title: '入库时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.storageTime == null) {
        return null;
      }
      return parseTime(record.storageTime);
    }
  },
  {
    key: 'expirationDays',
    dataIndex: 'expirationDays',
    title: '距离到期时间',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return `${record.expirationDays}天`;
    }
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '入库员',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'changeTime',
    dataIndex: 'changeTime',
    title: '更改时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.changeTime == null) {
        return null;
      }
      return parseTime(record.changeTime);
    }
  },
  {
    key: 'outbound',
    dataIndex: 'outbound',
    title: '出库员',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'auditing',
    dataIndex: 'auditing',
    title: '审核人',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'auditingTime',
    dataIndex: 'auditingTime',
    title: '审核时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.auditingTime == null) {
        return null;
      }
      return parseTime(record.auditingTime);
    }
  }
]);

const formListqr = [
  {
    type: 'input',
    key: 'inventory',
    label: '数量',
    placeholder: '请输入数量',
    span: 24
  }
];
const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);

function getData() {
  loading.value = true;
  planautoDryProcessselect({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...searchParams.value
  })
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item, index) => {
          item.index = index + 1;
        });
        tableData.value = data.list;
        pagination.total = data.total;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}

function getRowBgColor(record) {
  if (Number(record.failureState) === 3) {
    return {
      backgroundColor: 'rgb(243, 195, 195)'
    };
  }
  if (Number(record.failureState) === 2) {
    return {
      backgroundColor: 'rgb(238, 190, 140)'
    };
  }
  if (Number(record.failureState) === 1) {
    return {
      backgroundColor: 'rgb(150, 212, 150)'
    };
  }
  return '';
}
// autoDryProcessdelete
function deleteData() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择一条数据');
  }

  window.$modal?.confirm({
    title: `是否确认删除数据?`,

    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          autoDryProcessdelete(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('删除成功');
        } else {
          window.$message?.error('删除失败!');
        }
      });
    },
    onCancel: () => {}
  });
}
const detailsVisibleQrcode = ref(false);

const boundTitle = ref('');
const crDatas = ref({});
function outbound() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请选择数据!');
  }
  boundTitle.value = '出库';
  detailsVisibleQrcode.value = true;
}

function boundUpdata(val) {
  if (!crDatas.value.inventory) {
    return window.$message?.error('请输入数量!');
  }

  crDatas.value.id = selectedRowKeys.value[0];

  autoDryProcessoutbound(crDatas.value).then(({ error, data }) => {
    if (!error) {
      window.$message?.success('出库成功!');
      crDatas.value = {};
      detailsVisibleQrcode.value = false;
      selectedRowKeys.value = [];
      boundTitle.value = '';
      getData();
    }
  });
}
// autoDryProcessbatchAudit
function checkData() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择数据!');
  }

  window.$modal?.confirm({
    title: `是否确认审核数据?`,

    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          autoDryProcessbatchAudit(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('审核成功');
        } else {
          window.$message?.error('审核失败!');
        }
      });
    },
    onCancel: () => {}
  });
}
// autoDryProcessbatchRevoke
function fallback() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择数据!');
  }

  window.$modal?.confirm({
    title: `是否确认撤审数据?`,

    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          autoDryProcessbatchRevoke(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('撤审成功');
        } else {
          window.$message?.error('撤审失败!');
        }
      });
    },
    onCancel: () => {}
  });
}

function agvplanautoDryProcesstask() {
  autoDryProcesstask().then(({ error, data }) => {
    if (!error) {
      window.$message?.success('数据同步成功!');

      getData();
    }
  });
}
const currentRowId = ref(null);
function onDblclick(record, index) {
  return {
    onDblclick: event => {
      boundTitle.value = '出库';

      selectedRowKeys.value[0] = record.id;
      detailsVisibleQrcode.value = true;
    },
    style: {
      background: record.id === currentRowId.value ? '#BAEAFA' : '',
      ...getRowBgColor(record)
    },
    class: record.id === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.id;
    }
  };
}
getData();

function search() {
  pagination.current = 1;

  getData();
}

const tableFooterRef = ref(null);
const { height } = useElementSize(tableFooterRef);

const footerHeight = computed(() => {
  return `${height.value + 20}px`;
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="search()" @search="search()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="agvplanautoDryProcesstask">
          <span class="ml-3px">数据同步</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteData">
          <span class="ml-3px">删除</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="outbound">
          <span class="ml-3px">出库</span>
        </AButton>

        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="checkData">
          <span class="ml-3px">审核</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="fallback">
          <span class="ml-3px">撤审</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <STable
        :columns="columns"
        :data-source="tableData"
        size="small"
        bordered
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: tableSelectChange
        }"
        :custom-row="onDblclick"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        row-key="id"
        :default-expand-all-rows="true"
        :scroll="{ y: 'auto' }"
        :pagination="pagination"
        :row-height="23"
        class="has-footer-table h-full"
      >
        <template #footer>
          <div ref="tableFooterRef" style="display: flex">
            <div style="display: flex; line-height: 14px; margin-top: 5px; align-items: center">
              <div style="width: 20px; height: 14px; background-color: rgb(243, 195, 195)"></div>
              <span>背景为10天内过期</span>
            </div>
            <div style="display: flex; line-height: 14px; margin-top: 5px; align-items: center">
              <div style="width: 20px; height: 14px; background-color: rgb(238, 190, 140)"></div>
              <span>背景为15天内过期</span>
            </div>
            <div style="display: flex; line-height: 14px; margin-top: 5px; align-items: center">
              <div style="width: 20px; height: 14px; background-color: rgb(150, 212, 150)"></div>
              <span>背景为正常</span>
            </div>
          </div>
        </template>
      </STable>
    </ACard>

    <Modal
      v-model:visible="detailsVisibleQrcode"
      :destroy-on-close="true"
      :centered="true"
      :title="boundTitle"
      width="550px"
      height="350px"
    >
      <div class="event-form">
        <Form v-model:model="crDatas" :form-list="formListqr"></Form>
      </div>

      <template #footer>
        <div class="modal-footer">
          <AButton @click="detailsVisibleQrcode = false">关闭</AButton>
          <AButton @click="boundUpdata(boundTitle)">保存</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.surely-table-wrapper) {
  &.has-footer-table {
    .ant-spin-nested-loading {
      .ant-spin-container {
        .surely-table {
          height: calc(100% - 40px - v-bind('footerHeight')) !important;
        }
      }
    }
  }
}
</style>
